//定义全局变量
var menuGrid;// 表格
var dhxWins,editWin;
var oneMenuInfo,flag=-1;

// 页面布局
var pageObj = { type : "0100", height : [ 50, , 30 ], paging : true, size : 15};
var layoutContainer = create_layout(pageObj);
// 初始化操作
$(function() {
	initGrid();
    $('#pagingArea').css({"height":"30px","bottom":"5px","left":"1px"});//分页

});
// 初始化表格
function initGrid() {
	// 获取表格对象
	menuGrid = layoutContainer.grid[0];
	// 定义表格表头
	var columnsInfo = [ {  header : '菜单id', 	id : 'id', 			width : 80 },
	                    {  header : '父菜单id', 	id : 'parent_id', 	width : 80 },
	                    {  header : '菜单类型',  	id : 'menu_type',  	width : 80 ,	type:'combo'}, 
	                    {  header : '菜单名称',  	id : 'menu_name',  	width : 190 },
	                    {  header : '菜单url',  	id : 'menu_url',  	width : 250  },
		                {  header : '图标',  		id : 'picture_url', width : 80 },
	                    {  header : '排序',  		id : 'sort_num',  	width : 80 },
	                    {  header : '状态',  		id : 'status',  	width : '80' ,	type:'combo'},
	                    {  header : '备注',  		id : 'remark', 		width : '*', 	hidden:true},
	                    {  header : '创建时间',  	id : 'gmt_create',  width : '*'}
	                    ];
	// 创建表格
	dmjplugs.grid.createGrid({
		sm : 'ch',
		skin : 'dhx_skyblue',
		srcc : true,
		columns : columnsInfo
	}, menuGrid);
	menuGrid.setTotal(0);
    menuGrid.setColumnHidden(0,true);

    menuGrid.enableEditEvents(false, false, false);
	menuGrid.getColumnCombo(menuGrid.getColIndexById('status')).addOption(statusComboData);
	menuGrid.getColumnCombo(menuGrid.getColIndexById('menu_type')).addOption(menuTypeComboData);

	// 注册分页事件
	menuGrid.attachEvent("loadPagingData", function(first, limit) {
		findPageGrid(first, limit);
	});
	// 注册行点击事件
	menuGrid.attachEvent("onRowSelect", doOnRowSelected);
	menuGrid.attachEvent("onRowDblClicked", function () {
		doEdit('edit');
	});
	// 获取表格数据
	findPageGrid();
}
// 根据选择条件,获取表格数据
function findPageGrid(first, limit) {
	// 初始化表格为空表
	if (!limit) {
		first = 0;
		limit = menuGrid.getPageRowLimit();
		menuGrid.clearAll();
		menuGrid.setTotal(0);
	}
	// 分页组件数据
	var postData = "pageNo=" + parseInt(first / limit + 1) + "&pageSize="
			+ limit + "&pageCount=" + menuGrid.getPageTotal();
	if (typeof (search_Form) == 'object') {
		var formData = search_Form.getFormData();//获取查询表单数据
		var searchType=formData.searchType;
		//var searchKey=formData.searchKey;
        var searchKey=search_Form.getInput("searchKey").value;
		if($.trim(searchKey).length>0 ) postData+=(searchType==1?"&menuName=":searchType==2?"&aa=":"&bb=")+searchKey;
		if(formData.menu_type)	postData += "&menuType="+formData.menu_type;
		if(formData.status)	postData += "&status="+formData.status;
	}

	$.ajax({
		url : basePath + 'manageMenu/findPageData',
		type : 'post',
		dataType : 'json', // 返回的数据类型
		data : encodeURI(postData),
		success : function(data) {
			if(!data||!data.result){
        		$func.alert(data.message?data.message:'查询失败','red');
        		return;
        	}
            if(data.rowCount>0){
				menuGrid.parse(data.gridr, "json");
				menuGrid.setTotal(data.rowCount);
                menuGrid.uncheckAll();
				menuGrid.forEachRow(function(id){
					var pictureUrl = $.trim(menuGrid.cells(id, menuGrid.getColIndexById('picture_url')).getValue());
					if(pictureUrl&&pictureUrl.length>0&&(pictureUrl.indexOf('http://')!=-1 || pictureUrl.indexOf('https://')!=-1)&&pictureUrl.indexOf('pictureUrlImg')==-1){
						var url="<a href='"+pictureUrl+"' target='_blank'><img src='"+pictureUrl+"' class='pictureUrlImg'/></a>";
						menuGrid.cells(id, menuGrid.getColIndexById('picture_url')).setValue(url);
					}
				});
            }else{
            	$func.alert('未查询到菜单','red');
            }
			 
		}
	});
}
// ------------------------------------------------顶部操作区----------------------------------------------------------------------
// 顶部查询按钮 注册点击事件
function doOnButtFormInit() {
	if (typeof (butt_Form) == 'object') {
		butt_Form.attachEvent("onButtonClick", function(name, command) {
			if (command == 'add')// 新增
				doAdd('add');
			else if (command == 'edit')// 编辑
				doEdit('edit');
			else if (command == 'refresh')// 刷新
				doRefresh();
			else if (command == 'delete')// 删除用户
                doDelete();
		});
	}
}
//顶部查询框初始化	
function doOnSearchFormInit(){
	if (typeof(search_Form) != "object") return;
 	moduleSearchInit();
	search_Form.attachEvent("onButtonClick", function(name, command) {
		if (command == 'search') doRefresh();
		else if(command == 'reset') doReset();
	});
	
	var searchType_combo=search_Form.getCombo('searchType');
	searchType_combo.addOption(searchTypeComboData);
	searchType_combo.setComboValue('1');
	searchType_combo.readonly(true);
	
	var blockCombo=search_Form.getCombo('menu_type');
	blockCombo.addOption(menuTypeComboData);
	blockCombo.setComboValue('');
	blockCombo.readonly(true);
	
	var statusCombo=search_Form.getCombo('status');
	statusCombo.addOption(statusComboData);
	statusCombo.setComboValue('');
	statusCombo.readonly(true);
	
	search_Form.setItemFocus("searchKey");
    //回车事件
    $('input[name="searchKey"]').keydown(function(e){
        if(e.keyCode==13){
            doRefresh();
        }
    });
}
// 刷新按钮
function doRefresh() {
	//$("#freeze").html("<span>冻结账号</span>");
	var searchBlock_ = $('#searchForm>.dhxlist_obj_dhx_skyblue>.dhxlist_base>.block_item_label_left');
	searchBlock_.first().nextAll().css('display', 'none');
	$('#searchForm').removeClass('searchFormExpand');
	$('#toggleFormBtn').removeClass('toggleonFormButt').addClass( 'toggleFormButt');
	$('#tabSearch').hide();
	findPageGrid();
}

function doEdit(type) {
	if (type != 'edit')return;
	var menus = getCheckedRowsByGrid(menuGrid, menuGrid.getColIndexById('select'));
	if (menus == null || menus.length > 1) {
		$func.alert("请选择一行再操作[编辑]", "red");
		return;
	}
	oneMenuInfo = menus[0];
	if (!oneMenuInfo || !oneMenuInfo.id) {
		$func.alert("所选择行数据有问题,请选择其他行或者刷新页面重试", "red");
		return;
	}
	openWindow(type)
}

// --------------------------------------------------事件方法--------------------------------------------------------------------------
function doAdd(type) {
	if (type != 'add') return;
	openWindow(type)
}
function openWindow(type) {
	if(type == 'edit'){
		checkParam(oneMenuInfo.id);
	}else{
		flag=Math.floor(Math.random()*1000);
		checkParam(flag);//TODO 水平校验
	}
	if (!dhxWins) dhxWins = new dhtmlXWindows();
	dhxWins.setImagePath(basePP + "js/dhtmlx/dhtmlxWindows/codebase/imgs/");
	editWin = dhxWins.createWindow("editWin", 5, 5, 545, 370);
	editWin.center();
	editWin.setModal(true);
	editWin.bringToTop();
	editWin.setText("<span style=\"font-size:14px;\">"+ (type == "add" ? "新增菜单" : "编辑菜单") + "</span>");
	editWin.denyResize();
	editWin.button("minmax1").hide();
	editWin.button("park").hide();
	editWin.attachURL(basePath + "manageMenu/editMenu?type=" + type);
}



function doOnRowSelected(rowID, celInd) {
	editStatus = menuGrid.cells(rowID, menuGrid.getColIndexById('status')).getValue();
    $("#delete").html("<span>"+(editStatus=='enabled'?"失效":editStatus=='disabled'?"恢复":"恢复")+"</span>");
}

function doReset() {
	search_Form.setItemValue("searchKey", "");
	// 单个重置
//	var tcombo = search_Form.getCombo('searchType');
//	tcombo.setComboValue('');
//	tcombo.readonly(true);
	var statusCombo = search_Form.getCombo('status');
	statusCombo.setComboValue('');
	statusCombo.readonly(true);
	var menu_typeCombo = search_Form.getCombo('menu_type');
	menu_typeCombo.setComboValue('');
	menu_typeCombo.readonly(true);
	//批量重置
	search_Form.setFormData({
 
	});
}
//-------------------------------备份-----------------备份------------------------------------
function doDelete() {
	var menus = getCheckedRowsByGrid(menuGrid, menuGrid.getColIndexById('select'));
	if (menus == null || menus.length == 0) {
		$func.alert("至少选择一行再操作", "red");
		return;
	}
	//var menuIds = [];
	//$.each(menus, function(k, v) {
	//	menuIds.push(v.ID);
	//});
	var confirmArr = "是否失效菜单【" + menus[0].menu_name+ "】？ ";
    var id= $.trim(menus[0].id);
    if(!id){
        $func.alert("所选数据有问题,请刷新页面!",	"id");
        return;
    }
    //验证
    checkParam(id);

	var postData = "id=" +id;

    var status= $.trim(menus[0].status);
    if(status=='enabled'){
        postData += "&status=disabled"   ;
    }else{
        postData += "&status=enabled"   ;
		confirmArr = "是否恢复菜单【" + menus[0].menu_name+ "】？ ";
    }
	$func.confirm({
		content : confirmArr,
		ok : function() {
			$.ajax({
				url : basePath + 'manageMenu/changeState',
				type : 'post',
				dataType : 'json',
				data : postData,
				success : function(back) {
					if (!back || !back.result) {
						$func.alert(back.message?back.message : "操作失败！", "red");
						return;
					}
					$func.alert("操作成功",	"green");
					doRefresh();
				},
                error:function(xhr, textStatus, statusText){
                    $func.alert('请求失败,状态:'+textStatus+",信息:"+statusText, "red");
                }
			});
		}
	});
}
